<template>
  <view class="recordSave-page">
    <tb-tabs
      :tabList="tabList"
      v-model="activeName"
      @input="handleChangeTab"
    ></tb-tabs>
    <view class="record-info" :style="{ background: record.iconColor }">
      <i class="icon iconfont" :class="record.icon"></i>
      <span class="tag-name">{{ record.tagName }}</span>
      <span class="amount">{{ amountExpression }}</span>
      <!-- <input type="number" v-model="amountExpression" /> -->
    </view>
    <ul class="tag-content">
      <li
        class="tag-item"
        v-for="tag in tagSelectdNoDelList"
        :key="tag.name"
        @click="handleClickTag(tag)"
      >
        <view
          class="tag-icon"
          :style="{
            background: tag.id === record.tagId ? tag.iconColor : '#e8e8e8',
            color: tag.id === record.tagId ? '#fff' : '#888888',
          }"
        >
          <i :class="['icon', 'iconfont', tag.icon]"></i>
        </view>
        <span class="tag-name">{{ tag.name }}</span>
      </li>
      <li class="tag-item" @click="handleEditTag">
        <view class="tag-icon">
          <i :class="['icon', 'iconfont', 'icon-jiahao1']"></i>
        </view>
        <span class="tag-name">管理分类</span>
      </li>
    </ul>

    <!-- 键盘 -->
    <view class="keyboard">
      <view class="keyboard-tool">
        <view class="keyboard-tool-item">
          <i class="icon iconfont icon-xuexiziliao"></i>
          <span>{{ bookInfo.bookName }}</span>
        </view>
        <view class="keyboard-tool-item">
          <uni-datetime-picker
            type="datetime"
            :value="record.recordTime"
            return-type="timestamp"
            @change="handleTimeChange"
          >
            <template #default>
              <i class="icon iconfont icon-shijian"></i>
              <span>{{ $moment(record.recordTime).format('MM月DD日') }}</span>
            </template>
          </uni-datetime-picker>
        </view>
        <view class="keyboard-tool-item remark" @click="handleClickRemark">
          <i class="icon iconfont icon-beizhu"></i>
          <span>{{ record.remark || '添加备注...' }}</span>
        </view>
      </view>
      <view class="keyboard-grid">
        <ul class="keyboard-number">
          <li
            v-for="number in numberList"
            :key="number"
            @click="handleClickNumber(number)"
          >
            {{ number }}
          </li>
          <li @click="handleClickNumber('.')">.</li>
          <li @click="handleClickNumber(0)">0</li>
          <li>再记</li>
        </ul>
        <ul>
          <li @click="onBackSpace">
            <i class="icon iconfont icon-backspace"></i>
          </li>
          <li @click="handleClickAdd">+</li>
          <li @click="handleClickMinus">-</li>
          <li class="onSave" @click="onSave">
            {{ /^(?=.*(\+|\-))/.test(amountExpression) ? '=' : '完成' }}
          </li>
        </ul>
      </view>
    </view>

    <!-- 备注 -->
    <tb-popup ref="remarkPopup">
      <div class="remark-warp">
        <input type="text" v-model="remark" placeholder="请输入备注" />
        <div class="btn-group">
          <tb-button class="cancal-btn" @click="handleRemarkCancel">
            取消
          </tb-button>
          <tb-button class="confirm-btn" @click="handleRemarkConfirm">
            确定
          </tb-button>
        </div>
      </div>
    </tb-popup>
  </view>
</template>
<script lang="ts">
import { tag } from '@/type/books'
import { recordItem } from '@/type/records'
import Vue from 'vue'
import { mapState } from 'vuex'
export default Vue.extend({
  data() {
    return {
      activeName: '支出',
      type: 1, // 1-新增 2-编辑
      tabList: [
        { label: '支出', name: '支出' },
        { label: '收入', name: '收入' },
      ],
      record: {} as recordItem,
      tagList: [] as tag[],
      tagSelectdNoDelList: [] as tag[],
      numberList: [7, 8, 9, 4, 5, 6, 1, 2, 3],
      amountExpression: '0' as string,
      selectedTagIncome: {} as tag,
      selectedTagOutlay: {} as tag,
      remark: '', // 弹出层备注
    }
  },
  computed: {
    ...mapState('books', {
      bookInfo: (state: any) => state.bookInfo,
    }),
  },
  methods: {
    initData(record: recordItem) {
      this.activeName = record.type
    },
    // 点击切换分类
    handleChangeTab(tab: string) {
      console.log(tab)
      const tag: tag = {
        id: this.record.tagId,
        icon: this.record.icon as string,
        iconColor: this.record.iconColor as string,
        name: this.record.tagName,
        type: this.record.type,
      }
      this.tagSelectdNoDelList = this.bookInfo.tagVOList.filter(
        (tag: tag) => tag.type === tab
      )
      // 切换分类时，保留上次选择的标签
      if (tab === '收入') {
        this.selectedTagOutlay = tag
        this.handleClickTag(
          this.selectedTagIncome.id
            ? this.selectedTagIncome
            : this.tagSelectdNoDelList[0]
        )
      }
      if (tab === '支出') {
        this.selectedTagIncome = tag
        this.handleClickTag(
          this.selectedTagOutlay.id
            ? this.selectedTagOutlay
            : this.tagSelectdNoDelList[0]
        )
      }
    },
    // 点击标签
    handleClickTag(tag: tag) {
      this.record.tagName = tag.name
      this.record.iconColor = tag.iconColor as string
      this.record.icon = tag.icon
      this.record.tagId = tag.id as number
      this.record.type = tag.type
    },
    // 点击数字键盘
    handleClickNumber(number: string) {
      const num = String(number)
      if (this.amountExpression !== '0') {
        this.amountExpression += num
      } else {
        this.amountExpression = ['.'].includes(number)
          ? this.amountExpression + number
          : number
      }
    },
    // 点击+
    handleClickAdd(operator = true) {
      const expression = String(this.amountExpression)
      if (expression.indexOf('+') > -1) {
        const arr = expression.split('+')
        this.amountExpression = String(Number(arr[0]) + Number(arr[1]))
      }
      operator && (this.amountExpression += '+')
    },
    // 点击-
    handleClickMinus(operator = true) {
      const expression = String(this.amountExpression)
      if (expression.indexOf('-') > -1) {
        const arr = expression.split('-')
        this.amountExpression = String(Number(arr[0]) - Number(arr[1]))
      }
      operator && (this.amountExpression += '-')
    },
    // 点击回退
    onBackSpace() {
      this.amountExpression =
        this.amountExpression.length > 1
          ? this.amountExpression.slice(0, -1)
          : '0'
    },
    // 点击完成/=
    onSave() {
      if (/^(?=.*(\+))/.test(this.amountExpression))
        return this.handleClickAdd(false)
      if (/^(?=.*(\-))/.test(this.amountExpression))
        return this.handleClickMinus(false)

      if (Number(this.amountExpression) === 0) {
        uni.showToast({ title: '金额不能等于0', icon: 'none' })
        return
      }
      const params = {
        ...this.record,
        bookId: this.bookInfo.id,
        amount: Math.abs(Number(this.amountExpression)),
      }
      delete params.icon
      delete params.iconColor

      if (this.type === 1) {
        this.$api.postRecordApi(params).then((res: any) => {
          if (res.code === 1) {
            uni.switchTab({ url: '/pages/index/index' })
          }
        })
      } else {
        this.$api.putRecordApi(params).then((res: any) => {
          if (res.code === 1) {
            uni.switchTab({ url: '/pages/index/index' })
          }
        })
      }
    },
    // 管理分类
    handleEditTag() {
      uni.navigateTo({
        url: `/pages/tag/tagSetting?activeName=${this.activeName}&from=record`,
      })
    },
    // 编辑备注
    handleClickRemark() {
      ;(this.$refs.remarkPopup as any).open()
      this.remark = this.record.remark as string
    },
    // 编辑备注取消
    handleRemarkCancel() {
      ;(this.$refs.remarkPopup as any).close()
      this.remark = ''
    },
    // 编辑备注确定
    handleRemarkConfirm() {
      this.record.remark = this.remark
      this.handleRemarkCancel()
    },
    // 修改日期时间
    handleTimeChange(val: any) {
      console.log(val)
      this.record.recordTime = this.$moment(val).format('YYYY-MM-DD HH:mm:ss')
    },
  },
  onLoad(options: any) {
    console.log(options.record, this.bookInfo, this.tagSelectdNoDelList)
    this.type = options.record ? 2 : 1
    this.tagSelectdNoDelList = this.bookInfo.tagVOList.filter(
      (tag: tag) => tag.type === this.activeName
    )
    if (options.record) {
      this.record = JSON.parse(decodeURIComponent(options.record))
      this.activeName = this.record.type
      this.tagSelectdNoDelList = this.bookInfo.tagVOList.filter(
        (tag: tag) => tag.type === this.activeName
      )
    } else {
      const tag = this.tagSelectdNoDelList[0]
      this.record = {
        tagName: tag.name,
        icon: tag.icon,
        iconColor: tag.iconColor as string,
        type: tag.type,
        remark: '',
        amount: '0',
        recordTime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        tagId: tag.id,
      } as recordItem
    }
    this.amountExpression = (this.record.amount as string) || '0'
  },
})
</script>
<style lang="less" scoped>
.recordSave-page {
  width: 100%;
  height: 100%;
  padding: 0 48rpx;
  box-sizing: border-box;
  position: relative;
  .record-info {
    width: 100%;
    height: 150rpx;
    padding: 30rpx;
    box-sizing: border-box;
    margin-top: 30rpx;
    border-radius: 20rpx;
    color: #fff;
    display: flex;
    flex-direction: row;
    align-items: center;
    .iconfont {
      font-size: 48rpx;
      margin-right: 30rpx;
    }
    .tag-name {
      font-size: 30rpx;
    }
    .amount {
      flex: 1;
      text-align: right;
      font-size: 36rpx;
    }
  }
  .tag-content {
    margin-top: 30rpx;
    width: 100%;
    display: grid;
    grid-template-columns: repeat(5, 20%);
    justify-items: center;
    align-items: center;
    grid-row-gap: 40rpx;
    .tag-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      .tag-icon {
        width: 80rpx;
        height: 80rpx;
        border-radius: 20rpx;
        color: #888888;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 10rpx;
        position: relative;
        background: #e8e8e8;
        .iconfont {
          font-size: 48rpx;
        }
      }
      .tag-name {
        font-size: 24rpx;
        color: #333;
      }
    }
  }

  .keyboard {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 50%;
    background: #fff;
    .keyboard-tool {
      height: 80rpx;
      border-bottom: 2rpx solid #eee;
      display: flex;
      align-items: center;
      .keyboard-tool-item {
        line-height: 80rpx;
        .iconfont {
          font-size: #333;
          font-size: 30rpx;
          margin: 0 5rpx 0 30rpx;
        }
        &.remark {
          flex-grow: 1;
        }
      }
    }
    .keyboard-grid {
      width: 100%;
      height: calc(100% - 80rpx);
      display: flex;
      ul {
        width: 25%;
        display: grid;
        grid-template-columns: repeat(1, 100%);
        grid-template-rows: repeat(4, 25%);
      }
      ul.keyboard-number {
        width: 75%;
        display: grid;
        grid-template-columns: repeat(3, 33.3%);
        grid-template-rows: repeat(4, 25%);
      }
      li {
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: bold;
        font-size: 40rpx;
        &.onSave {
          background: #87cefa;
        }
        .iconfont {
          font-size: 50rpx;
        }
      }
    }
  }
}
.remark-warp {
  height: 200rpx;
  background: #fff;
  padding: 30rpx 48rpx;
  box-sizing: border-box;
  input {
    width: 100%;
    background: #e8e8e8;
    border-radius: 10rpx;
    line-height: 60rpx;
    height: 60rpx;
    padding: 0 20rpx;
    box-sizing: border-box;
    font-size: 30rpx;
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 20rpx;
    .custom-btn {
      width: 100rpx;
      font-size: 20rpx;
      margin: 0 10rpx 0 0;
      &.cancal-btn {
        background: #fff;
        border: 2rpx solid #87cefa;
        color: #87cefa;
      }
      &.confirm-btn {
        background: #87cefa;
        color: #fff;
      }
    }
  }
}
</style>